package com.sanjiayi.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.sanjiayi.config.QiniuConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@Component
public class QiniuUtils {

    @Autowired
    private QiniuConfig qiniuConfig;

    private UploadManager uploadManager;
    private Auth auth;

    @Autowired
    public void init() {
        try {
            log.info("初始化七牛云配置...");
            log.info("AccessKey: {}", qiniuConfig.getAccessKey());
            log.info("Bucket: {}", qiniuConfig.getBucket());
            log.info("Domain: {}", qiniuConfig.getDomain());
            
            Configuration cfg = new Configuration(Region.autoRegion());
            uploadManager = new UploadManager(cfg);
            auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
            log.info("七牛云配置初始化成功");
        } catch (Exception e) {
            log.error("七牛云配置初始化失败: {}", e.getMessage(), e);
            throw new RuntimeException("七牛云配置初始化失败", e);
        }
    }

    /**
     * 上传字节数组
     */
    public boolean upload(byte[] bytes, String key) {
        try {
            log.info("开始上传文件: {}", key);
            String upToken = auth.uploadToken(qiniuConfig.getBucket());
            log.info("获取上传凭证成功");
            
            Response response = uploadManager.put(bytes, key, upToken);
            log.info("文件上传结果: {}", response.toString());
            
            if (response.isOK()) {
                log.info("文件上传成功: {}", key);
                return true;
            } else {
                log.error("文件上传失败: {}, 错误信息: {}", key, response.error);
                return false;
            }
        } catch (QiniuException e) {
            log.error("七牛云上传失败: {}, 错误码: {}, 错误信息: {}", 
                    key, e.code(), e.response.toString(), e);
            return false;
        }
    }

    /**
     * 上传文件
     */
    public boolean uploadFile(MultipartFile file, String key) {
        try {
            log.info("开始读取文件: {}, 大小: {} bytes", file.getOriginalFilename(), file.getSize());
            byte[] bytes = file.getBytes();
            log.info("文件读取成功，开始上传");
            return upload(bytes, key);
        } catch (IOException e) {
            log.error("文件读取失败: {}", e.getMessage(), e);
            return false;
        }
    }
} 